<?php

namespace App\Http\Controllers\Api\Admin;

use App\Exceptions\ConditionException;
use App\Http\Requests\Admin\UserRequest;
use App\Http\Resources\Admin\UserResource;
use App\Services\UserService;
use Illuminate\Http\Request;
use App\Http\Controllers\ApiController;
use Illuminate\Support\Facades\Cache;

/**
 * Class AdminController
 * @package App\Http\Controllers\Api\Admin\User
 */
class AdminController extends ApiController
{

    /**
     * @var UserService
     */
    private $service;

    /**
     * AdminController constructor.
     * @param UserService $service
     */
    public function __construct(UserService $service)
    {
        $this->service = $service;
        $this->middleware('jwt:admin');
    }

    /**
     * 获取列表信息
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function index(Request $request)
    {
        $this->hasPermission('admin-main');
        $map = $request->all();
        $list = $this->service->seek($map);

        return $this->success(UserResource::collection($list));
    }

    /**
     * 获取详情
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function show($id)
    {
        $this->hasPermission('admin-main');
        $info = $this->service->find($id);
        return $this->success(new UserResource($info));
    }


    /**
     * 创建
     * @param UserRequest $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function store(UserRequest $request)
    {
        $this->hasPermission('admin-opera');
        $map = $request->all();
        $map['password'] = \Hash::make($map['password']);
        $info = $this->service->create($map);
        return $this->success(new UserResource($info));
    }

    /**
     * 修改
     * @param $id
     * @param UserRequest $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Prettus\Validator\Exceptions\ValidatorException
     */
    public function update($id, UserRequest $request)
    {
        // 可以修改个人信息
        if ($this->user()->id != $id) {
            $this->hasPermission('admin-opera');
        }
        $data = $request->all();
        if (isset($data['password']) && $data['password']) {
            $data['password'] = \Hash::make($data['password']);
        }
        $info = $this->service->find($id);
        $info->fill($data)->save();
        return $this->success(new UserResource($info));
    }

    /**
     * 删除记录
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function destroy($id)
    {
        $this->hasPermission('admin-del');
        if ($id == 1) {
            throw new ConditionException('不支持删除超级账号！');
        }
        $this->service->delete($id);
        return $this->message('删除成功！');
    }
}
